/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mudalov.rec.util.webui;

import com.sun.data.provider.RowKey;
import com.sun.webui.jsf.event.TableSelectPhaseListener;

import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;

/**
 *
 * @author MU
 */
public class TableSelection {

    private TableSelectPhaseListener tspl = null; // Phase listener.

    private String tableVarName;

    public TableSelection(String varName) {
        tspl = new TableSelectPhaseListener();
        tableVarName = varName;
    }

    public void clear() {
        tspl.clear();
    }

    public boolean isKeepSelected() {
        return tspl.isKeepSelected();
    }

    public void keepSelected(boolean keepSelected) {
        tspl.keepSelected(keepSelected);
    }

    public Object getSelected() {
        return tspl.getSelected(getTableRow());
    }

    public void setSelected(Object object) {
        RowKey rowKey = getTableRow();
        if (rowKey != null) {
            tspl.setSelected(rowKey, object);
        }
    }

    public Object getSelectedValue() {
        RowKey rowKey = getTableRow();
        return (rowKey != null) ? rowKey.getRowId() : null;
    }

    public boolean getSelectedState() {
        // Typically, selected state is tested by comparing the selected and
        // selectedValue properties. In this example, however, the phase
        // listener value is not null when selected.
        return getSelectedState(getTableRow());
    }

    // Get the selected state.
    public boolean getSelectedState(RowKey rowKey) {
        return tspl.isSelected(rowKey);
    }

    private RowKey getTableRow() {
        FacesContext context = FacesContext.getCurrentInstance();
        ValueBinding vb = context.getApplication().createValueBinding(
            "#{" + tableVarName + ".tableRow}");
        return (RowKey) vb.getValue(context);
    }
}
